package com.kb.controller;

import com.alibaba.fastjson.JSONObject;
import com.kb.annotation.UserLoginToken;
import com.kb.common.ApiResponse;
import com.kb.entity.User;
import com.kb.service.UserService;
import com.kb.service.impl.gc.CallLimitService;
import com.kb.util.TokenUtil;
import com.kb.util.TokenUtil2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/login")
public class LoginController {


    @Resource
    private UserService userService;
    @Resource
    private CallLimitService callLimitService;

    @Resource
    private TokenUtil2 tokenUtil2;
    @RequestMapping("/toLogin")
    @ResponseBody
    public ApiResponse toLogin(String userName, String userPassword, HttpServletResponse response){
        User user = userService.loing(userName, userPassword);
        JSONObject jsonObject = new JSONObject();

        if(Objects.isNull(user)){
            return ApiResponse.error("账号或者密码错误，请重试！");
        }

        String token = TokenUtil.getTokenSecret(userName, userPassword);
        jsonObject.put("token", token);
        response.setHeader("token", token);
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        response.addCookie(cookie);

        return ApiResponse.success(jsonObject);
    }

    @UserLoginToken
    @RequestMapping("/list")
    @ResponseBody
    public ApiResponse list(HttpServletRequest request){
        String userName = TokenUtil.getUserNameFromToken(request);

        if (!callLimitService.canCall(userName)) {
            return ApiResponse.error("您已超出每日调用限制，请明天再试！");
        }
        List<User> userList = userService.getUserList();
        return  ApiResponse.success(userList);
    }
//    @UserLoginToken
    @RequestMapping("/test")
    @ResponseBody
    public ApiResponse test(){
        return  ApiResponse.success("请求成功");
    }

}
